package flume.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import org.apache.commons.compress.utils.Charsets;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.Interceptor;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class CustomerInterceptor implements Interceptor {
    private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @Override
    public void initialize() {

    }

    @Override
    public Event intercept(Event event) {
        final String eventBody = new String(event.getBody(), Charsets.UTF_8);
        final Map<String, String> headers = event.getHeaders();
        final String[] bodyArr = eventBody.split("\\s+");

        try {
            String jsonStr = bodyArr[6];
            if (Strings.isNullOrEmpty(jsonStr)) {
                return null;
            }

            final JSONObject jsonObject = JSON.parseObject(jsonStr);
            String timeStr = "";

            if (headers.getOrDefault("logtype", "").equals("start")) {
                timeStr = jsonObject.getJSONObject("app_active").getString("time");
            } else {
                final JSONArray jsonArray = jsonObject.getJSONArray("lagou_event");
                if (jsonArray.size() > 0) {
                    timeStr = jsonArray.getJSONObject(0).getString("time");
                }
            }

            final long timeStamp = Long.parseLong(timeStr);
            final String date = formatter.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(timeStamp), ZoneId.systemDefault()));

            headers.put("logtime", date);
            event.setHeaders(headers);
        } catch (Exception e) {
            headers.put("logtime", "unknown");
            event.setHeaders(headers);
        }
        return event;
    }

    @Override
    public List<Event> intercept(List<Event> list) {
        final ArrayList<Event> events = new ArrayList<>();
        for (Event event : list) {
            final Event out = intercept(event);
            if (out != null) {
                events.add(out);
            }
        }
        return events;
    }

    @Override
    public void close() {

    }

    public static class Builder implements Interceptor.Builder {

        @Override
        public Interceptor build() {
            return new CustomerInterceptor();
        }

        @Override
        public void configure(Context context) {

        }
    }
}
